/*
 * StringInput.cpp
 *
 *  Created on: 10 feb 2010
 *      Author: Andreas
 */

#include "StringInput.h"
#include "FontManager.h"
#include <iostream>

using namespace std;

StringInput::StringInput(int x, int y, string font) {
	SDL_EnableUNICODE( SDL_ENABLE );
	str = "";

	xpos = x;
	ypos = y;
	this->font = font;
	active = false;
}

StringInput::~StringInput() {
	SDL_EnableUNICODE( SDL_DISABLE );
}

string StringInput::handleInput(SDL_Event *e) {
	// Only if input is active
	if (active) {
		Uint16 allowed[] = {(Uint16)'<', (Uint16)'>', (Uint16)'(', (Uint16)')',
				(Uint16)':', (Uint16)'_', (Uint16)'=', (Uint16)'\'', (Uint16)'/',
				(Uint16)' ', (Uint16)'"', (Uint16)'.', (Uint16)','
		};
		int allowed_num = 13;

		if (e->type == SDL_KEYDOWN) {
			//if (str.length() <= 16) {

			Uint16 c = e->key.keysym.unicode;

			// Digits
			if (c >= (Uint16)'0' && c <= (Uint16)'9') {
				str += (char)c;
			}
			// Lowercase
			else if (c >= (Uint16)'a' && c <= (Uint16)'z') {
				str += (char)c;
			}
			// Uppercase
			else if (c >= (Uint16)'A' && c <= (Uint16)'Z') {
				str += (char)c;
			}
			// Signs
			for (int i=0; i<allowed_num; i++) {
				if (c == allowed[i]) {
					str += (char)c;
				}
			}

			//}
			if( ( e->key.keysym.sym == SDLK_BACKSPACE ) && ( str.length() != 0 ) ) {
				//Remove a character from the end
				str.erase( str.length() - 1 );
			}
			else if( ( e->key.keysym.sym == SDLK_RETURN ) && ( str.length() != 0 ) ) {
				//Remove a character from the end
				string ret = str;
				str.clear();
				return ret;
			}
		}
	}
	return "";
}

void StringInput::draw() {
	FontManager::drawText(str, xpos, ypos, font);
}

void StringInput::setActive(bool b) {
	active = b;
	if (!active) {
		str.clear();
	}
}
